from selenium.webdriver.remote.webdriver import WebDriver, WebElement

from utils.selenium.perform import WPerform, FindType


def run(perform: WPerform):
    # 点击到验证码登录
    nav_btn_element: WebElement = perform.fint(find_type=FindType.class_name, find_key='ant-tabs-tab', multiple=True,
                                       find_index=1)
    nav_btn_element.click()

    username_element: WebElement = perform.fint(find_type=FindType.id, find_key='userName')

    username_element.send_keys('18320101263')

    code_element: WebElement = perform.fint(find_type=FindType.id, find_key='code')
    code_element.send_keys('111206')

    submit_element: WebElement = perform.fint(find_type=FindType.class_name,
                                              find_key='antd-pro-components-login-index-submit')

    submit_element.click()

    perform.sleep(3)

    titles = ['商品管理', '预付优惠管理', '套餐包管理']


    perform.send_msg('打开商品管理菜单')
    # 打开商品管理菜单
    menu_element: WebElement = find_element_with_title(titles[0], perform, 'ant-menu-submenu.ant-menu-submenu-inline')
    if not menu_element:
        perform.send_err('【%s】未查到' % titles[0])
    menu_element.click()
    perform.sleep(2)

    perform.send_msg('打开 预付优惠管理 页面')
    # 打开 预付优惠管理 页面
    sub_menu_element: WebElement = find_element_with_title(titles[1], perform, 'ant-menu-item',
                                                           super_element=menu_element)
    if not sub_menu_element:
        perform.send_err('【%s】未查到' % titles[1])
    sub_menu_element.click()
    perform.sleep(2)

    perform.send_msg('打开套餐包管理，进入Vue项目')
    # 打开套餐包管理
    sub1_menu_element: WebElement = find_element_with_title(titles[2], perform, 'ant-menu-item',
                                                            super_element=menu_element)
    if not sub1_menu_element:
        perform.send_err('【%s】未查到' % titles[2])
    sub1_menu_element.click()
    perform.sleep(7)

    # 判断当前项目是否在Vue项目
    perform.send_msg('当前项目 %s' % 'vue' if check_is_vue(perform) else 'react')

    perform.send_msg('Vue 项目跳转回来')
    # Vue 项目跳回来
    sub2_menu_element: WebElement = find_element_with_title(titles[1], perform, 'el-menu-item')
    sub2_menu_element.click()


def find_element_with_title(title: str, perform: WPerform, find_class: str, super_element=None):
    elements: list = perform.fint(find_type=FindType.class_name,
                                  find_key=find_class,
                                  multiple=True,
                                  highlighted=False,
                                  super_element=super_element)
    for element in elements:
        if element.text == title:
            return element


def check_is_vue(perform: WPerform):
    return '-vue' in perform.driver.current_url